package com.example.propertymanagement.service;

import com.example.propertymanagement.dto.OwnerDTO;
import com.example.propertymanagement.entity.Owner;
import com.example.propertymanagement.repository.OwnerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * OwnerService：业主服务层，处理业主相关的业务逻辑
 */
@Service
public class OwnerService {

    @Autowired
    private OwnerRepository ownerRepository;

    /**
     * 根据业主名称查找业主
     * @param memberName 业主名称
     * @return 业主DTO列表
     */
    public List<OwnerDTO> getOwnersByName(String memberName) {
        List<Owner> owners = ownerRepository.findByMemberName(memberName);  // 查找业主
        return owners.stream().map(this::convertToDTO).collect(Collectors.toList());  // 转换为DTO
    }

    /**
     * 根据小区名称查找业主
     * @param communityName 小区名称
     * @return 业主DTO列表
     */
    public List<OwnerDTO> getOwnersByCommunity(String communityName) {
        List<Owner> owners = ownerRepository.findByCommunity_CommunityName(communityName);  // 查找业主
        return owners.stream().map(this::convertToDTO).collect(Collectors.toList());  // 转换为DTO
    }

    /**
     * 根据业主姓名进行模糊查找
     * @param memberName 业主名称
     * @return 业主DTO列表
     */
    public List<OwnerDTO> searchOwnersByName(String memberName) {
        List<Owner> owners = ownerRepository.findByMemberNameContaining(memberName);  // 模糊查询
        return owners.stream().map(this::convertToDTO).collect(Collectors.toList());  // 转换为DTO
    }

    /**
     * 根据身份证号查找业主
     * @param idCard 身份证号
     * @return 业主DTO
     */
    public OwnerDTO getOwnerByIdCard(String idCard) {
        Owner owner = ownerRepository.findByIdCard(idCard);  // 根据身份证号查找业主
        return owner != null ? convertToDTO(owner) : null;  // 如果找到业主，转换为DTO
    }

    /**
     * 查找所有业主
     * @return 业主DTO列表
     */
    public List<OwnerDTO> getAllOwners() {
        List<Owner> owners = ownerRepository.findAll();  // 查找所有业主
        return owners.stream().map(this::convertToDTO).collect(Collectors.toList());  // 转换为DTO
    }

    /**
     * 查找指定ID的业主
     * @param ownerId 业主ID
     * @return 业主DTO
     */
    public Optional<OwnerDTO> getOwnerById(Integer ownerId) {
        Optional<Owner> owner = ownerRepository.findById(ownerId);  // 根据ID查找业主
        return owner.map(this::convertToDTO);  // 如果找到业主，转换为DTO
    }

    /**
     * 添加新业主
     * @param owner 新业主对象
     * @return 新增的业主DTO
     */
    public OwnerDTO addOwner(Owner owner) {
        Owner savedOwner = ownerRepository.save(owner);  // 保存新业主
        return convertToDTO(savedOwner);  // 转换为DTO并返回
    }

    /**
     * 更新业主信息
     * @param owner 业主对象（包含ID）
     * @return 更新后的业主DTO
     */
    public OwnerDTO updateOwner(Owner owner) {
        if (ownerRepository.existsById(owner.getId())) {
            Owner updatedOwner = ownerRepository.save(owner);  // 更新业主信息
            return convertToDTO(updatedOwner);  // 转换为DTO并返回
        } else {
            throw new RuntimeException("业主不存在，无法更新！");  // 如果业主不存在，抛出异常
        }
    }

    /**
     * 删除指定ID的业主
     * @param ownerId 业主ID
     */
    public void deleteOwner(Integer ownerId) {
        if (ownerRepository.existsById(ownerId)) {
            ownerRepository.deleteById(ownerId);  // 删除业主
        } else {
            throw new RuntimeException("业主不存在，无法删除！");  // 如果业主不存在，抛出异常
        }
    }

    /**
     * 将 Owner 实体转换为 OwnerDTO
     * @param owner 业主实体
     * @return OwnerDTO 数据传输对象
     */
    private OwnerDTO convertToDTO(Owner owner) {
        OwnerDTO ownerDTO = new OwnerDTO();
        ownerDTO.setId(owner.getId());
        ownerDTO.setMemberName(owner.getMemberName());
        ownerDTO.setContactPhone(owner.getContactPhone());
        ownerDTO.setGender(owner.getGender());
        ownerDTO.setMemberType(owner.getMemberType());
        ownerDTO.setIdCard(owner.getIdCard());
        ownerDTO.setBirthDate(owner.getBirthDate());
        ownerDTO.setOccupation(owner.getOccupation());
        ownerDTO.setCreateTime(owner.getCreateTime());
        // 可以继续添加其他字段转换
        return ownerDTO;
    }
}